home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / platform.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  52.3 KB  |  1,635 lines

  1. #! /usr/bin/python2.6
  2.  
  3. """ This module tries to retrieve as much platform-identifying data as
  4.     possible. It makes this information available via function APIs.
  5.  
  6.     If called from the command line, it prints the platform
  7.     information concatenated as single string to stdout. The output
  8.     format is useable as part of a filename.
  9.  
  10. """
  11. #    This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
  12. #    If you find problems, please submit bug reports/patches via the
  13. #    Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
  14. #
  15. #    Note: Please keep this module compatible to Python 1.5.2.
  16. #
  17. #    Still needed:
  18. #    * more support for WinCE
  19. #    * support for MS-DOS (PythonDX ?)
  20. #    * support for Amiga and other still unsupported platforms running Python
  21. #    * support for additional Linux distributions
  22. #
  23. #    Many thanks to all those who helped adding platform-specific
  24. #    checks (in no particular order):
  25. #
  26. #      Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  27. #      Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  28. #      Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  29. #      Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  30. #      Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  31. #      Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
  32. #
  33. #    History:
  34. #
  35. #    <see CVS and SVN checkin messages for history>
  36. #
  37. #    1.0.6 - added linux_distribution()
  38. #    1.0.5 - fixed Java support to allow running the module on Jython
  39. #    1.0.4 - added IronPython support
  40. #    1.0.3 - added normalization of Windows system name
  41. #    1.0.2 - added more Windows support
  42. #    1.0.1 - reformatted to make doc.py happy
  43. #    1.0.0 - reformatted a bit and checked into Python CVS
  44. #    0.8.0 - added sys.version parser and various new access
  45. #            APIs (python_version(), python_compiler(), etc.)
  46. #    0.7.2 - fixed architecture() to use sizeof(pointer) where available
  47. #    0.7.1 - added support for Caldera OpenLinux
  48. #    0.7.0 - some fixes for WinCE; untabified the source file
  49. #    0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  50. #            vms_lib.getsyi() configured
  51. #    0.6.1 - added code to prevent 'uname -p' on platforms which are
  52. #            known not to support it
  53. #    0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  54. #            did some cleanup of the interfaces - some APIs have changed
  55. #    0.5.5 - fixed another type in the MacOS code... should have
  56. #            used more coffee today ;-)
  57. #    0.5.4 - fixed a few typos in the MacOS code
  58. #    0.5.3 - added experimental MacOS support; added better popen()
  59. #            workarounds in _syscmd_ver() -- still not 100% elegant
  60. #            though
  61. #    0.5.2 - fixed uname() to return '' instead of 'unknown' in all
  62. #            return values (the system uname command tends to return
  63. #            'unknown' instead of just leaving the field emtpy)
  64. #    0.5.1 - included code for slackware dist; added exception handlers
  65. #            to cover up situations where platforms don't have os.popen
  66. #            (e.g. Mac) or fail on socket.gethostname(); fixed libc
  67. #            detection RE
  68. #    0.5.0 - changed the API names referring to system commands to *syscmd*;
  69. #            added java_ver(); made syscmd_ver() a private
  70. #            API (was system_ver() in previous versions) -- use uname()
  71. #            instead; extended the win32_ver() to also return processor
  72. #            type information
  73. #    0.4.0 - added win32_ver() and modified the platform() output for WinXX
  74. #    0.3.4 - fixed a bug in _follow_symlinks()
  75. #    0.3.3 - fixed popen() and "file" command invokation bugs
  76. #    0.3.2 - added architecture() API and support for it in platform()
  77. #    0.3.1 - fixed syscmd_ver() RE to support Windows NT
  78. #    0.3.0 - added system alias support
  79. #    0.2.3 - removed 'wince' again... oh well.
  80. #    0.2.2 - added 'wince' to syscmd_ver() supported platforms
  81. #    0.2.1 - added cache logic and changed the platform string format
  82. #    0.2.0 - changed the API to use functions instead of module globals
  83. #            since some action take too long to be run on module import
  84. #    0.1.0 - first release
  85. #
  86. #    You can always get the latest version of this module at:
  87. #
  88. #             http://www.egenix.com/files/python/platform.py
  89. #
  90. #    If that URL should fail, try contacting the author.
  91.  
  92. __copyright__ = """
  93.     Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  94.     Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
  95.  
  96.     Permission to use, copy, modify, and distribute this software and its
  97.     documentation for any purpose and without fee or royalty is hereby granted,
  98.     provided that the above copyright notice appear in all copies and that
  99.     both that copyright notice and this permission notice appear in
  100.     supporting documentation or portions thereof, including modifications,
  101.     that you make.
  102.  
  103.     EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
  104.     THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  105.     FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  106.     INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  107.     FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  108.     NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  109.     WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  110.  
  111. """
  112.  
  113. __version__ = '1.0.6'
  114.  
  115. import sys,string,os,re
  116.  
  117. ### Platform specific APIs
  118.  
  119. _libc_search = re.compile(r'(__libc_init)'
  120.                           '|'
  121.                           '(GLIBC_([0-9.]+))'
  122.                           '|'
  123.                           '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
  124.  
  125. def libc_ver(executable=sys.executable,lib='',version='',
  126.  
  127.              chunksize=2048):
  128.  
  129.     """ Tries to determine the libc version that the file executable
  130.         (which defaults to the Python interpreter) is linked against.
  131.  
  132.         Returns a tuple of strings (lib,version) which default to the
  133.         given parameters in case the lookup fails.
  134.  
  135.         Note that the function has intimate knowledge of how different
  136.         libc versions add symbols to the executable and thus is probably
  137.         only useable for executables compiled using gcc.
  138.  
  139.         The file is read and scanned in chunks of chunksize bytes.
  140.  
  141.     """
  142.     if hasattr(os.path, 'realpath'):
  143.         # Python 2.2 introduced os.path.realpath(); it is used
  144.         # here to work around problems with Cygwin not being
  145.         # able to open symlinks for reading
  146.         executable = os.path.realpath(executable)
  147.     f = open(executable,'rb')
  148.     binary = f.read(chunksize)
  149.     pos = 0
  150.     while 1:
  151.         m = _libc_search.search(binary,pos)
  152.         if not m:
  153.             binary = f.read(chunksize)
  154.             if not binary:
  155.                 break
  156.             pos = 0
  157.             continue
  158.         libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
  159.         if libcinit and not lib:
  160.             lib = 'libc'
  161.         elif glibc:
  162.             if lib != 'glibc':
  163.                 lib = 'glibc'
  164.                 version = glibcversion
  165.             elif glibcversion > version:
  166.                 version = glibcversion
  167.         elif so:
  168.             if lib != 'glibc':
  169.                 lib = 'libc'
  170.                 if soversion > version:
  171.                     version = soversion
  172.                 if threads and version[-len(threads):] != threads:
  173.                     version = version + threads
  174.         pos = m.end()
  175.     f.close()
  176.     return lib,version
  177.  
  178. def _dist_try_harder(distname,version,id):
  179.  
  180.     """ Tries some special tricks to get the distribution
  181.         information in case the default method fails.
  182.  
  183.         Currently supports older SuSE Linux, Caldera OpenLinux and
  184.         Slackware Linux distributions.
  185.  
  186.     """
  187.     if os.path.exists('/var/adm/inst-log/info'):
  188.         # SuSE Linux stores distribution information in that file
  189.         info = open('/var/adm/inst-log/info').readlines()
  190.         distname = 'SuSE'
  191.         for line in info:
  192.             tv = string.split(line)
  193.             if len(tv) == 2:
  194.                 tag,value = tv
  195.             else:
  196.                 continue
  197.             if tag == 'MIN_DIST_VERSION':
  198.                 version = string.strip(value)
  199.             elif tag == 'DIST_IDENT':
  200.                 values = string.split(value,'-')
  201.                 id = values[2]
  202.         return distname,version,id
  203.  
  204.     if os.path.exists('/etc/.installed'):
  205.         # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  206.         info = open('/etc/.installed').readlines()
  207.         for line in info:
  208.             pkg = string.split(line,'-')
  209.             if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  210.                 # XXX does Caldera support non Intel platforms ? If yes,
  211.                 #     where can we find the needed id ?
  212.                 return 'OpenLinux',pkg[1],id
  213.  
  214.     if os.path.isdir('/usr/lib/setup'):
  215.         # Check for slackware verson tag file (thanks to Greg Andruk)
  216.         verfiles = os.listdir('/usr/lib/setup')
  217.         for n in range(len(verfiles)-1, -1, -1):
  218.             if verfiles[n][:14] != 'slack-version-':
  219.                 del verfiles[n]
  220.         if verfiles:
  221.             verfiles.sort()
  222.             distname = 'slackware'
  223.             version = verfiles[-1][14:]
  224.             return distname,version,id
  225.  
  226.     return distname,version,id
  227.  
  228. _release_filename = re.compile(r'(\w+)[-_](release|version)')
  229. _lsb_release_version = re.compile(r'(.+)'
  230.                                    ' release '
  231.                                    '([\d.]+)'
  232.                                    '[^(]*(?:\((.+)\))?')
  233. _release_version = re.compile(r'([^0-9]+)'
  234.                                '(?: release )?'
  235.                                '([\d.]+)'
  236.                                '[^(]*(?:\((.+)\))?')
  237.  
  238. # See also http://www.novell.com/coolsolutions/feature/11251.html
  239. # and http://linuxmafia.com/faq/Admin/release-files.html
  240. # and http://data.linux-ntfs.org/rpm/whichrpm
  241. # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
  242.  
  243. _supported_dists = (
  244.     'SuSE', 'debian', 'fedora', 'redhat', 'centos',
  245.     'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
  246.     'UnitedLinux', 'turbolinux')
  247.  
  248. def _parse_release_file(firstline):
  249.  
  250.     # Default to empty 'version' and 'id' strings.  Both defaults are used
  251.     # when 'firstline' is empty.  'id' defaults to empty when an id can not
  252.     # be deduced.
  253.     version = ''
  254.     id = ''
  255.  
  256.     # Parse the first line
  257.     m = _lsb_release_version.match(firstline)
  258.     if m is not None:
  259.         # LSB format: "distro release x.x (codename)"
  260.         return tuple(m.groups())
  261.  
  262.     # Pre-LSB format: "distro x.x (codename)"
  263.     m = _release_version.match(firstline)
  264.     if m is not None:
  265.         return tuple(m.groups())
  266.  
  267.     # Unkown format... take the first two words
  268.     l = string.split(string.strip(firstline))
  269.     if l:
  270.         version = l[0]
  271.         if len(l) > 1:
  272.             id = l[1]
  273.     return '', version, id
  274.  
  275. def _test_parse_release_file():
  276.  
  277.     for input, output in (
  278.         # Examples of release file contents:
  279.         ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
  280.         ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
  281.         ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
  282.         ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
  283.         ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
  284.         ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
  285.         ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
  286.         ('CentOS release 4', ('CentOS', '4', None))
  287.         ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
  288.         ):
  289.         parsed = _parse_release_file(input)
  290.         if parsed != output:
  291.             print (input, parsed)
  292.  
  293. _distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I)
  294. _release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I)
  295. _codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I)
  296.  
  297. def linux_distribution(distname='', version='', id='',
  298.  
  299.                        supported_dists=_supported_dists,
  300.                        full_distribution_name=1):
  301.  
  302.     """ Tries to determine the name of the Linux OS distribution name.
  303.  
  304.         The function first looks for a distribution release file in
  305.         /etc and then reverts to _dist_try_harder() in case no
  306.         suitable files are found.
  307.  
  308.         supported_dists may be given to define the set of Linux
  309.         distributions to look for. It defaults to a list of currently
  310.         supported Linux distributions identified by their release file
  311.         name.
  312.  
  313.         If full_distribution_name is true (default), the full
  314.         distribution read from the OS is returned. Otherwise the short
  315.         name taken from supported_dists is used.
  316.  
  317.         Returns a tuple (distname,version,id) which default to the
  318.         args given as parameters.
  319.  
  320.     """
  321.     # check for the Debian/Ubuntu /etc/lsb-release file first, needed so
  322.     # that the distribution doesn't get identified as Debian.
  323.     try:
  324.         etclsbrel = open("/etc/lsb-release", "rU")
  325.         for line in etclsbrel:
  326.             m = _distributor_id_file_re.search(line)
  327.             if m:
  328.                 _u_distname = m.group(1).strip()
  329.             m = _release_file_re.search(line)
  330.             if m:
  331.                 _u_version = m.group(1).strip()
  332.             m = _codename_file_re.search(line)
  333.             if m:
  334.                 _u_id = m.group(1).strip()
  335.         if _u_distname and _u_version:
  336.             return (_u_distname, _u_version, _u_id)
  337.     except (EnvironmentError, UnboundLocalError):
  338.             pass
  339.  
  340.     try:
  341.         etc = os.listdir('/etc')
  342.     except os.error:
  343.         # Probably not a Unix system
  344.         return distname,version,id
  345.     etc.sort()
  346.     for file in etc:
  347.         m = _release_filename.match(file)
  348.         if m is not None:
  349.             _distname,dummy = m.groups()
  350.             if _distname in supported_dists:
  351.                 distname = _distname
  352.                 break
  353.     else:
  354.         return _dist_try_harder(distname,version,id)
  355.  
  356.     # Read the first line
  357.     f = open('/etc/'+file, 'r')
  358.     firstline = f.readline()
  359.     f.close()
  360.     _distname, _version, _id = _parse_release_file(firstline)
  361.  
  362.     if _distname and full_distribution_name:
  363.         distname = _distname
  364.     if _version:
  365.         version = _version
  366.     if _id:
  367.         id = _id
  368.     return distname, version, id
  369.  
  370. # To maintain backwards compatibility:
  371.  
  372. def dist(distname='',version='',id='',
  373.  
  374.          supported_dists=_supported_dists):
  375.  
  376.     """ Tries to determine the name of the Linux OS distribution name.
  377.  
  378.         The function first looks for a distribution release file in
  379.         /etc and then reverts to _dist_try_harder() in case no
  380.         suitable files are found.
  381.  
  382.         Returns a tuple (distname,version,id) which default to the
  383.         args given as parameters.
  384.  
  385.     """
  386.     return linux_distribution(distname, version, id,
  387.                               supported_dists=supported_dists,
  388.                               full_distribution_name=0)
  389.  
  390. class _popen:
  391.  
  392.     """ Fairly portable (alternative) popen implementation.
  393.  
  394.         This is mostly needed in case os.popen() is not available, or
  395.         doesn't work as advertised, e.g. in Win9X GUI programs like
  396.         PythonWin or IDLE.
  397.  
  398.         Writing to the pipe is currently not supported.
  399.  
  400.     """
  401.     tmpfile = ''
  402.     pipe = None
  403.     bufsize = None
  404.     mode = 'r'
  405.  
  406.     def __init__(self,cmd,mode='r',bufsize=None):
  407.  
  408.         if mode != 'r':
  409.             raise ValueError,'popen()-emulation only supports read mode'
  410.         import tempfile
  411.         self.tmpfile = tmpfile = tempfile.mktemp()
  412.         os.system(cmd + ' > %s' % tmpfile)
  413.         self.pipe = open(tmpfile,'rb')
  414.         self.bufsize = bufsize
  415.         self.mode = mode
  416.  
  417.     def read(self):
  418.  
  419.         return self.pipe.read()
  420.  
  421.     def readlines(self):
  422.  
  423.         if self.bufsize is not None:
  424.             return self.pipe.readlines()
  425.  
  426.     def close(self,
  427.  
  428.               remove=os.unlink,error=os.error):
  429.  
  430.         if self.pipe:
  431.             rc = self.pipe.close()
  432.         else:
  433.             rc = 255
  434.         if self.tmpfile:
  435.             try:
  436.                 remove(self.tmpfile)
  437.             except error:
  438.                 pass
  439.         return rc
  440.  
  441.     # Alias
  442.     __del__ = close
  443.  
  444. def popen(cmd, mode='r', bufsize=None):
  445.  
  446.     """ Portable popen() interface.
  447.     """
  448.     # Find a working popen implementation preferring win32pipe.popen
  449.     # over os.popen over _popen
  450.     popen = None
  451.     if os.environ.get('OS','') == 'Windows_NT':
  452.         # On NT win32pipe should work; on Win9x it hangs due to bugs
  453.         # in the MS C lib (see MS KnowledgeBase article Q150956)
  454.         try:
  455.             import win32pipe
  456.         except ImportError:
  457.             pass
  458.         else:
  459.             popen = win32pipe.popen
  460.     if popen is None:
  461.         if hasattr(os,'popen'):
  462.             popen = os.popen
  463.             # Check whether it works... it doesn't in GUI programs
  464.             # on Windows platforms
  465.             if sys.platform == 'win32': # XXX Others too ?
  466.                 try:
  467.                     popen('')
  468.                 except os.error:
  469.                     popen = _popen
  470.         else:
  471.             popen = _popen
  472.     if bufsize is None:
  473.         return popen(cmd,mode)
  474.     else:
  475.         return popen(cmd,mode,bufsize)
  476.  
  477. def _norm_version(version, build=''):
  478.  
  479.     """ Normalize the version and build strings and return a single
  480.         version string using the format major.minor.build (or patchlevel).
  481.     """
  482.     l = string.split(version,'.')
  483.     if build:
  484.         l.append(build)
  485.     try:
  486.         ints = map(int,l)
  487.     except ValueError:
  488.         strings = l
  489.     else:
  490.         strings = map(str,ints)
  491.     version = string.join(strings[:3],'.')
  492.     return version
  493.  
  494. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  495.                          '.*'
  496.                          'Version ([\d.]+))')
  497.  
  498. def _syscmd_ver(system='', release='', version='',
  499.  
  500.                supported_platforms=('win32','win16','dos','os2')):
  501.  
  502.     """ Tries to figure out the OS version used and returns
  503.         a tuple (system,release,version).
  504.  
  505.         It uses the "ver" shell command for this which is known
  506.         to exists on Windows, DOS and OS/2. XXX Others too ?
  507.  
  508.         In case this fails, the given parameters are used as
  509.         defaults.
  510.  
  511.     """
  512.     if sys.platform not in supported_platforms:
  513.         return system,release,version
  514.  
  515.     # Try some common cmd strings
  516.     for cmd in ('ver','command /c ver','cmd /c ver'):
  517.         try:
  518.             pipe = popen(cmd)
  519.             info = pipe.read()
  520.             if pipe.close():
  521.                 raise os.error,'command failed'
  522.             # XXX How can I supress shell errors from being written
  523.             #     to stderr ?
  524.         except os.error,why:
  525.             #print 'Command %s failed: %s' % (cmd,why)
  526.             continue
  527.         except IOError,why:
  528.             #print 'Command %s failed: %s' % (cmd,why)
  529.             continue
  530.         else:
  531.             break
  532.     else:
  533.         return system,release,version
  534.  
  535.     # Parse the output
  536.     info = string.strip(info)
  537.     m = _ver_output.match(info)
  538.     if m is not None:
  539.         system,release,version = m.groups()
  540.         # Strip trailing dots from version and release
  541.         if release[-1] == '.':
  542.             release = release[:-1]
  543.         if version[-1] == '.':
  544.             version = version[:-1]
  545.         # Normalize the version and build strings (eliminating additional
  546.         # zeros)
  547.         version = _norm_version(version)
  548.     return system,release,version
  549.  
  550. def _win32_getvalue(key,name,default=''):
  551.  
  552.     """ Read a value for name from the registry key.
  553.  
  554.         In case this fails, default is returned.
  555.  
  556.     """
  557.     try:
  558.         # Use win32api if available
  559.         from win32api import RegQueryValueEx
  560.     except ImportError:
  561.         # On Python 2.0 and later, emulate using _winreg
  562.         import _winreg
  563.         RegQueryValueEx = _winreg.QueryValueEx
  564.     try:
  565.         return RegQueryValueEx(key,name)
  566.     except:
  567.         return default
  568.  
  569. def win32_ver(release='',version='',csd='',ptype=''):
  570.  
  571.     """ Get additional version information from the Windows Registry
  572.         and return a tuple (version,csd,ptype) referring to version
  573.         number, CSD level and OS type (multi/single
  574.         processor).
  575.  
  576.         As a hint: ptype returns 'Uniprocessor Free' on single
  577.         processor NT machines and 'Multiprocessor Free' on multi
  578.         processor machines. The 'Free' refers to the OS version being
  579.         free of debugging code. It could also state 'Checked' which
  580.         means the OS version uses debugging code, i.e. code that
  581.         checks arguments, ranges, etc. (Thomas Heller).
  582.  
  583.         Note: this function works best with Mark Hammond's win32
  584.         package installed, but also on Python 2.3 and later. It
  585.         obviously only runs on Win32 compatible platforms.
  586.  
  587.     """
  588.     # XXX Is there any way to find out the processor type on WinXX ?
  589.     # XXX Is win32 available on Windows CE ?
  590.     #
  591.     # Adapted from code posted by Karl Putland to comp.lang.python.
  592.     #
  593.     # The mappings between reg. values and release names can be found
  594.     # here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
  595.  
  596.     # Import the needed APIs
  597.     try:
  598.         import win32api
  599.         from win32api import RegQueryValueEx, RegOpenKeyEx, \
  600.              RegCloseKey, GetVersionEx
  601.         from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
  602.              VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
  603.     except ImportError:
  604.         # Emulate the win32api module using Python APIs
  605.         try:
  606.             sys.getwindowsversion
  607.         except AttributeError:
  608.             # No emulation possible, so return the defaults...
  609.             return release,version,csd,ptype
  610.         else:
  611.             # Emulation using _winreg (added in Python 2.0) and
  612.             # sys.getwindowsversion() (added in Python 2.3)
  613.             import _winreg
  614.             GetVersionEx = sys.getwindowsversion
  615.             RegQueryValueEx = _winreg.QueryValueEx
  616.             RegOpenKeyEx = _winreg.OpenKeyEx
  617.             RegCloseKey = _winreg.CloseKey
  618.             HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
  619.             VER_PLATFORM_WIN32_WINDOWS = 1
  620.             VER_PLATFORM_WIN32_NT = 2
  621.             VER_NT_WORKSTATION = 1
  622.             VER_NT_SERVER = 3
  623.             REG_SZ = 1
  624.  
  625.     # Find out the registry key and some general version infos
  626.     winver = GetVersionEx()
  627.     maj,min,buildno,plat,csd = winver
  628.     version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
  629.     if hasattr(winver, "service_pack"):
  630.         if winver.service_pack != "":
  631.             csd = 'SP%s' % winver.service_pack_major
  632.     else:
  633.         if csd[:13] == 'Service Pack ':
  634.             csd = 'SP' + csd[13:]
  635.     if plat == VER_PLATFORM_WIN32_WINDOWS:
  636.         regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
  637.         # Try to guess the release name
  638.         if maj == 4:
  639.             if min == 0:
  640.                 release = '95'
  641.             elif min == 10:
  642.                 release = '98'
  643.             elif min == 90:
  644.                 release = 'Me'
  645.             else:
  646.                 release = 'postMe'
  647.         elif maj == 5:
  648.             release = '2000'
  649.     elif plat == VER_PLATFORM_WIN32_NT:
  650.         regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
  651.         if maj <= 4:
  652.             release = 'NT'
  653.         elif maj == 5:
  654.             if min == 0:
  655.                 release = '2000'
  656.             elif min == 1:
  657.                 release = 'XP'
  658.             elif min == 2:
  659.                 release = '2003Server'
  660.             else:
  661.                 release = 'post2003'
  662.         elif maj == 6:
  663.             if hasattr(winver, "product_type"):
  664.                 product_type = winver.product_type
  665.             else:
  666.                 product_type = VER_NT_WORKSTATION
  667.                 # Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
  668.                 # or help from the registry, we cannot properly identify
  669.                 # non-workstation versions.
  670.                 try:
  671.                     key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  672.                     name, type = RegQueryValueEx(key, "ProductName")
  673.                     # Discard any type that isn't REG_SZ
  674.                     if type == REG_SZ and name.find("Server") != -1:
  675.                         product_type = VER_NT_SERVER
  676.                 except WindowsError:
  677.                     # Use default of VER_NT_WORKSTATION
  678.                     pass
  679.  
  680.             if min == 0:
  681.                 if product_type == VER_NT_WORKSTATION:
  682.                     release = 'Vista'
  683.                 else:
  684.                     release = '2008Server'
  685.             elif min == 1:
  686.                 if product_type == VER_NT_WORKSTATION:
  687.                     release = '7'
  688.                 else:
  689.                     release = '2008ServerR2'
  690.             else:
  691.                 release = 'post2008Server'
  692.     else:
  693.         if not release:
  694.             # E.g. Win3.1 with win32s
  695.             release = '%i.%i' % (maj,min)
  696.         return release,version,csd,ptype
  697.  
  698.     # Open the registry key
  699.     try:
  700.         keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
  701.         # Get a value to make sure the key exists...
  702.         RegQueryValueEx(keyCurVer, 'SystemRoot')
  703.     except:
  704.         return release,version,csd,ptype
  705.  
  706.     # Parse values
  707.     #subversion = _win32_getvalue(keyCurVer,
  708.     #                            'SubVersionNumber',
  709.     #                            ('',1))[0]
  710.     #if subversion:
  711.     #   release = release + subversion # 95a, 95b, etc.
  712.     build = _win32_getvalue(keyCurVer,
  713.                             'CurrentBuildNumber',
  714.                             ('',1))[0]
  715.     ptype = _win32_getvalue(keyCurVer,
  716.                            'CurrentType',
  717.                            (ptype,1))[0]
  718.  
  719.     # Normalize version
  720.     version = _norm_version(version,build)
  721.  
  722.     # Close key
  723.     RegCloseKey(keyCurVer)
  724.     return release,version,csd,ptype
  725.  
  726. def _mac_ver_lookup(selectors,default=None):
  727.  
  728.     from gestalt import gestalt
  729.     import MacOS
  730.     l = []
  731.     append = l.append
  732.     for selector in selectors:
  733.         try:
  734.             append(gestalt(selector))
  735.         except (RuntimeError, MacOS.Error):
  736.             append(default)
  737.     return l
  738.  
  739. def _bcd2str(bcd):
  740.  
  741.     return hex(bcd)[2:]
  742.  
  743. def _mac_ver_gestalt():
  744.     """
  745.         Thanks to Mark R. Levinson for mailing documentation links and
  746.         code examples for this function. Documentation for the
  747.         gestalt() API is available online at:
  748.  
  749.            http://www.rgaros.nl/gestalt/
  750.     """
  751.     # Check whether the version info module is available
  752.     try:
  753.         import gestalt
  754.         import MacOS
  755.     except ImportError:
  756.         return None
  757.     # Get the infos
  758.     sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
  759.     # Decode the infos
  760.     if sysv:
  761.         major = (sysv & 0xFF00) >> 8
  762.         minor = (sysv & 0x00F0) >> 4
  763.         patch = (sysv & 0x000F)
  764.  
  765.         if (major, minor) >= (10, 4):
  766.             # the 'sysv' gestald cannot return patchlevels
  767.             # higher than 9. Apple introduced 3 new
  768.             # gestalt codes in 10.4 to deal with this
  769.             # issue (needed because patch levels can
  770.             # run higher than 9, such as 10.4.11)
  771.             major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
  772.             release = '%i.%i.%i' %(major, minor, patch)
  773.         else:
  774.             release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  775.  
  776.     if sysa:
  777.         machine = {0x1: '68k',
  778.                    0x2: 'PowerPC',
  779.                    0xa: 'i386'}.get(sysa,'')
  780.  
  781.     return release,versioninfo,machine
  782.  
  783. def _mac_ver_xml():
  784.     fn = '/System/Library/CoreServices/SystemVersion.plist'
  785.     if not os.path.exists(fn):
  786.         return None
  787.  
  788.     try:
  789.         import plistlib
  790.     except ImportError:
  791.         return None
  792.  
  793.     pl = plistlib.readPlist(fn)
  794.     release = pl['ProductVersion']
  795.     versioninfo=('', '', '')
  796.     machine = os.uname()[4]
  797.     if machine in ('ppc', 'Power Macintosh'):
  798.         # for compatibility with the gestalt based code
  799.         machine = 'PowerPC'
  800.  
  801.     return release,versioninfo,machine
  802.  
  803.  
  804. def mac_ver(release='',versioninfo=('','',''),machine=''):
  805.  
  806.     """ Get MacOS version information and return it as tuple (release,
  807.         versioninfo, machine) with versioninfo being a tuple (version,
  808.         dev_stage, non_release_version).
  809.  
  810.         Entries which cannot be determined are set to the paramter values
  811.         which default to ''. All tuple entries are strings.
  812.     """
  813.  
  814.     # First try reading the information from an XML file which should
  815.     # always be present
  816.     info = _mac_ver_xml()
  817.     if info is not None:
  818.         return info
  819.  
  820.     # If that doesn't work for some reason fall back to reading the
  821.     # information using gestalt calls.
  822.     info = _mac_ver_gestalt()
  823.     if info is not None:
  824.         return info
  825.  
  826.     # If that also doesn't work return the default values
  827.     return release,versioninfo,machine
  828.  
  829. def _java_getprop(name,default):
  830.  
  831.     from java.lang import System
  832.     try:
  833.         value = System.getProperty(name)
  834.         if value is None:
  835.             return default
  836.         return value
  837.     except AttributeError:
  838.         return default
  839.  
  840. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  841.  
  842.     """ Version interface for Jython.
  843.  
  844.         Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  845.         a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  846.         tuple (os_name,os_version,os_arch).
  847.  
  848.         Values which cannot be determined are set to the defaults
  849.         given as parameters (which all default to '').
  850.  
  851.     """
  852.     # Import the needed APIs
  853.     try:
  854.         import java.lang
  855.     except ImportError:
  856.         return release,vendor,vminfo,osinfo
  857.  
  858.     vendor = _java_getprop('java.vendor', vendor)
  859.     release = _java_getprop('java.version', release)
  860.     vm_name, vm_release, vm_vendor = vminfo
  861.     vm_name = _java_getprop('java.vm.name', vm_name)
  862.     vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  863.     vm_release = _java_getprop('java.vm.version', vm_release)
  864.     vminfo = vm_name, vm_release, vm_vendor
  865.     os_name, os_version, os_arch = osinfo
  866.     os_arch = _java_getprop('java.os.arch', os_arch)
  867.     os_name = _java_getprop('java.os.name', os_name)
  868.     os_version = _java_getprop('java.os.version', os_version)
  869.     osinfo = os_name, os_version, os_arch
  870.  
  871.     return release, vendor, vminfo, osinfo
  872.  
  873. ### System name aliasing
  874.  
  875. def system_alias(system,release,version):
  876.  
  877.     """ Returns (system,release,version) aliased to common
  878.         marketing names used for some systems.
  879.  
  880.         It also does some reordering of the information in some cases
  881.         where it would otherwise cause confusion.
  882.  
  883.     """
  884.     if system == 'Rhapsody':
  885.         # Apple's BSD derivative
  886.         # XXX How can we determine the marketing release number ?
  887.         return 'MacOS X Server',system+release,version
  888.  
  889.     elif system == 'SunOS':
  890.         # Sun's OS
  891.         if release < '5':
  892.             # These releases use the old name SunOS
  893.             return system,release,version
  894.         # Modify release (marketing release = SunOS release - 3)
  895.         l = string.split(release,'.')
  896.         if l:
  897.             try:
  898.                 major = int(l[0])
  899.             except ValueError:
  900.                 pass
  901.             else:
  902.                 major = major - 3
  903.                 l[0] = str(major)
  904.                 release = string.join(l,'.')
  905.         if release < '6':
  906.             system = 'Solaris'
  907.         else:
  908.             # XXX Whatever the new SunOS marketing name is...
  909.             system = 'Solaris'
  910.  
  911.     elif system == 'IRIX64':
  912.         # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  913.         # is really a version and not a different platform, since 32-bit
  914.         # apps are also supported..
  915.         system = 'IRIX'
  916.         if version:
  917.             version = version + ' (64bit)'
  918.         else:
  919.             version = '64bit'
  920.  
  921.     elif system in ('win32','win16'):
  922.         # In case one of the other tricks
  923.         system = 'Windows'
  924.  
  925.     return system,release,version
  926.  
  927. ### Various internal helpers
  928.  
  929. def _platform(*args):
  930.  
  931.     """ Helper to format the platform string in a filename
  932.         compatible format e.g. "system-version-machine".
  933.     """
  934.     # Format the platform string
  935.     platform = string.join(
  936.         map(string.strip,
  937.             filter(len, args)),
  938.         '-')
  939.  
  940.     # Cleanup some possible filename obstacles...
  941.     replace = string.replace
  942.     platform = replace(platform,' ','_')
  943.     platform = replace(platform,'/','-')
  944.     platform = replace(platform,'\\','-')
  945.     platform = replace(platform,':','-')
  946.     platform = replace(platform,';','-')
  947.     platform = replace(platform,'"','-')
  948.     platform = replace(platform,'(','-')
  949.     platform = replace(platform,')','-')
  950.  
  951.     # No need to report 'unknown' information...
  952.     platform = replace(platform,'unknown','')
  953.  
  954.     # Fold '--'s and remove trailing '-'
  955.     while 1:
  956.         cleaned = replace(platform,'--','-')
  957.         if cleaned == platform:
  958.             break
  959.         platform = cleaned
  960.     while platform[-1] == '-':
  961.         platform = platform[:-1]
  962.  
  963.     return platform
  964.  
  965. def _node(default=''):
  966.  
  967.     """ Helper to determine the node name of this machine.
  968.     """
  969.     try:
  970.         import socket
  971.     except ImportError:
  972.         # No sockets...
  973.         return default
  974.     try:
  975.         return socket.gethostname()
  976.     except socket.error:
  977.         # Still not working...
  978.         return default
  979.  
  980. # os.path.abspath is new in Python 1.5.2:
  981. if not hasattr(os.path,'abspath'):
  982.  
  983.     def _abspath(path,
  984.  
  985.                  isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  986.                  normpath=os.path.normpath):
  987.  
  988.         if not isabs(path):
  989.             path = join(getcwd(), path)
  990.         return normpath(path)
  991.  
  992. else:
  993.  
  994.     _abspath = os.path.abspath
  995.  
  996. def _follow_symlinks(filepath):
  997.  
  998.     """ In case filepath is a symlink, follow it until a
  999.         real file is reached.
  1000.     """
  1001.     filepath = _abspath(filepath)
  1002.     while os.path.islink(filepath):
  1003.         filepath = os.path.normpath(
  1004.             os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
  1005.     return filepath
  1006.  
  1007. def _syscmd_uname(option,default=''):
  1008.  
  1009.     """ Interface to the system's uname command.
  1010.     """
  1011.     if sys.platform in ('dos','win32','win16','os2'):
  1012.         # XXX Others too ?
  1013.         return default
  1014.     try:
  1015.         f = os.popen('uname %s 2> /dev/null' % option)
  1016.     except (AttributeError,os.error):
  1017.         return default
  1018.     output = string.strip(f.read())
  1019.     rc = f.close()
  1020.     if not output or rc:
  1021.         return default
  1022.     else:
  1023.         return output
  1024.  
  1025. def _syscmd_file(target,default=''):
  1026.  
  1027.     """ Interface to the system's file command.
  1028.  
  1029.         The function uses the -b option of the file command to have it
  1030.         ommit the filename in its output and if possible the -L option
  1031.         to have the command follow symlinks. It returns default in
  1032.         case the command should fail.
  1033.  
  1034.     """
  1035.     if sys.platform in ('dos','win32','win16','os2'):
  1036.         # XXX Others too ?
  1037.         return default
  1038.     target = _follow_symlinks(target).replace('"', '\\"')
  1039.     try:
  1040.         f = os.popen('file "%s" 2> /dev/null' % target)
  1041.     except (AttributeError,os.error):
  1042.         return default
  1043.     output = string.strip(f.read())
  1044.     rc = f.close()
  1045.     if not output or rc:
  1046.         return default
  1047.     else:
  1048.         return output
  1049.  
  1050. ### Information about the used architecture
  1051.  
  1052. # Default values for architecture; non-empty strings override the
  1053. # defaults given as parameters
  1054. _default_architecture = {
  1055.     'win32': ('','WindowsPE'),
  1056.     'win16': ('','Windows'),
  1057.     'dos': ('','MSDOS'),
  1058. }
  1059.  
  1060. _architecture_split = re.compile(r'[\s,]').split
  1061.  
  1062. def architecture(executable=sys.executable,bits='',linkage=''):
  1063.  
  1064.     """ Queries the given executable (defaults to the Python interpreter
  1065.         binary) for various architecture information.
  1066.  
  1067.         Returns a tuple (bits,linkage) which contains information about
  1068.         the bit architecture and the linkage format used for the
  1069.         executable. Both values are returned as strings.
  1070.  
  1071.         Values that cannot be determined are returned as given by the
  1072.         parameter presets. If bits is given as '', the sizeof(pointer)
  1073.         (or sizeof(long) on Python version < 1.5.2) is used as
  1074.         indicator for the supported pointer size.
  1075.  
  1076.         The function relies on the system's "file" command to do the
  1077.         actual work. This is available on most if not all Unix
  1078.         platforms. On some non-Unix platforms where the "file" command
  1079.         does not exist and the executable is set to the Python interpreter
  1080.         binary defaults from _default_architecture are used.
  1081.  
  1082.     """
  1083.     # Use the sizeof(pointer) as default number of bits if nothing
  1084.     # else is given as default.
  1085.     if not bits:
  1086.         import struct
  1087.         try:
  1088.             size = struct.calcsize('P')
  1089.         except struct.error:
  1090.             # Older installations can only query longs
  1091.             size = struct.calcsize('l')
  1092.         bits = str(size*8) + 'bit'
  1093.  
  1094.     # Get data from the 'file' system command
  1095.     if executable:
  1096.         output = _syscmd_file(executable, '')
  1097.     else:
  1098.         output = ''
  1099.  
  1100.     if not output and \
  1101.        executable == sys.executable:
  1102.         # "file" command did not return anything; we'll try to provide
  1103.         # some sensible defaults then...
  1104.         if sys.platform in _default_architecture:
  1105.             b, l = _default_architecture[sys.platform]
  1106.             if b:
  1107.                 bits = b
  1108.             if l:
  1109.                 linkage = l
  1110.         return bits, linkage
  1111.  
  1112.     # Split the output into a list of strings omitting the filename
  1113.     fileout = _architecture_split(output)[1:]
  1114.  
  1115.     if 'executable' not in fileout:
  1116.         # Format not supported
  1117.         return bits,linkage
  1118.  
  1119.     # Bits
  1120.     if '32-bit' in fileout:
  1121.         bits = '32bit'
  1122.     elif 'N32' in fileout:
  1123.         # On Irix only
  1124.         bits = 'n32bit'
  1125.     elif '64-bit' in fileout:
  1126.         bits = '64bit'
  1127.  
  1128.     # Linkage
  1129.     if 'ELF' in fileout:
  1130.         linkage = 'ELF'
  1131.     elif 'PE' in fileout:
  1132.         # E.g. Windows uses this format
  1133.         if 'Windows' in fileout:
  1134.             linkage = 'WindowsPE'
  1135.         else:
  1136.             linkage = 'PE'
  1137.     elif 'COFF' in fileout:
  1138.         linkage = 'COFF'
  1139.     elif 'MS-DOS' in fileout:
  1140.         linkage = 'MSDOS'
  1141.     else:
  1142.         # XXX the A.OUT format also falls under this class...
  1143.         pass
  1144.  
  1145.     return bits,linkage
  1146.  
  1147. ### Portable uname() interface
  1148.  
  1149. _uname_cache = None
  1150.  
  1151. def uname():
  1152.  
  1153.     """ Fairly portable uname interface. Returns a tuple
  1154.         of strings (system,node,release,version,machine,processor)
  1155.         identifying the underlying platform.
  1156.  
  1157.         Note that unlike the os.uname function this also returns
  1158.         possible processor information as an additional tuple entry.
  1159.  
  1160.         Entries which cannot be determined are set to ''.
  1161.  
  1162.     """
  1163.     global _uname_cache
  1164.     no_os_uname = 0
  1165.  
  1166.     if _uname_cache is not None:
  1167.         return _uname_cache
  1168.  
  1169.     processor = ''
  1170.  
  1171.     # Get some infos from the builtin os.uname API...
  1172.     try:
  1173.         system,node,release,version,machine = os.uname()
  1174.     except AttributeError:
  1175.         no_os_uname = 1
  1176.  
  1177.     if no_os_uname or not filter(None, (system, node, release, version, machine)):
  1178.         # Hmm, no there is either no uname or uname has returned
  1179.         #'unknowns'... we'll have to poke around the system then.
  1180.         if no_os_uname:
  1181.             system = sys.platform
  1182.             release = ''
  1183.             version = ''
  1184.             node = _node()
  1185.             machine = ''
  1186.  
  1187.         use_syscmd_ver = 01
  1188.  
  1189.         # Try win32_ver() on win32 platforms
  1190.         if system == 'win32':
  1191.             release,version,csd,ptype = win32_ver()
  1192.             if release and version:
  1193.                 use_syscmd_ver = 0
  1194.             # Try to use the PROCESSOR_* environment variables
  1195.             # available on Win XP and later; see
  1196.             # http://support.microsoft.com/kb/888731 and
  1197.             # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  1198.             if not machine:
  1199.                 machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  1200.             if not processor:
  1201.                 processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  1202.  
  1203.         # Try the 'ver' system command available on some
  1204.         # platforms
  1205.         if use_syscmd_ver:
  1206.             system,release,version = _syscmd_ver(system)
  1207.             # Normalize system to what win32_ver() normally returns
  1208.             # (_syscmd_ver() tends to return the vendor name as well)
  1209.             if system == 'Microsoft Windows':
  1210.                 system = 'Windows'
  1211.             elif system == 'Microsoft' and release == 'Windows':
  1212.                 # Under Windows Vista and Windows Server 2008,
  1213.                 # Microsoft changed the output of the ver command. The
  1214.                 # release is no longer printed.  This causes the
  1215.                 # system and release to be misidentified.
  1216.                 system = 'Windows'
  1217.                 if '6.0' == version[:3]:
  1218.                     release = 'Vista'
  1219.                 else:
  1220.                     release = ''
  1221.  
  1222.         # In case we still don't know anything useful, we'll try to
  1223.         # help ourselves
  1224.         if system in ('win32','win16'):
  1225.             if not version:
  1226.                 if system == 'win32':
  1227.                     version = '32bit'
  1228.                 else:
  1229.                     version = '16bit'
  1230.             system = 'Windows'
  1231.  
  1232.         elif system[:4] == 'java':
  1233.             release,vendor,vminfo,osinfo = java_ver()
  1234.             system = 'Java'
  1235.             version = string.join(vminfo,', ')
  1236.             if not version:
  1237.                 version = vendor
  1238.  
  1239.         elif os.name == 'mac':
  1240.             release,(version,stage,nonrel),machine = mac_ver()
  1241.             system = 'MacOS'
  1242.  
  1243.     # System specific extensions
  1244.     if system == 'OpenVMS':
  1245.         # OpenVMS seems to have release and version mixed up
  1246.         if not release or release == '0':
  1247.             release = version
  1248.             version = ''
  1249.         # Get processor information
  1250.         try:
  1251.             import vms_lib
  1252.         except ImportError:
  1253.             pass
  1254.         else:
  1255.             csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  1256.             if (cpu_number >= 128):
  1257.                 processor = 'Alpha'
  1258.             else:
  1259.                 processor = 'VAX'
  1260.     if not processor:
  1261.         # Get processor information from the uname system command
  1262.         processor = _syscmd_uname('-p','')
  1263.  
  1264.     #If any unknowns still exist, replace them with ''s, which are more portable
  1265.     if system == 'unknown':
  1266.         system = ''
  1267.     if node == 'unknown':
  1268.         node = ''
  1269.     if release == 'unknown':
  1270.         release = ''
  1271.     if version == 'unknown':
  1272.         version = ''
  1273.     if machine == 'unknown':
  1274.         machine = ''
  1275.     if processor == 'unknown':
  1276.         processor = ''
  1277.  
  1278.     #  normalize name
  1279.     if system == 'Microsoft' and release == 'Windows':
  1280.         system = 'Windows'
  1281.         release = 'Vista'
  1282.  
  1283.     _uname_cache = system,node,release,version,machine,processor
  1284.     return _uname_cache
  1285.  
  1286. ### Direct interfaces to some of the uname() return values
  1287.  
  1288. def system():
  1289.  
  1290.     """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  1291.  
  1292.         An empty string is returned if the value cannot be determined.
  1293.  
  1294.     """
  1295.     return uname()[0]
  1296.  
  1297. def node():
  1298.  
  1299.     """ Returns the computer's network name (which may not be fully
  1300.         qualified)
  1301.  
  1302.         An empty string is returned if the value cannot be determined.
  1303.  
  1304.     """
  1305.     return uname()[1]
  1306.  
  1307. def release():
  1308.  
  1309.     """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1310.  
  1311.         An empty string is returned if the value cannot be determined.
  1312.  
  1313.     """
  1314.     return uname()[2]
  1315.  
  1316. def version():
  1317.  
  1318.     """ Returns the system's release version, e.g. '#3 on degas'
  1319.  
  1320.         An empty string is returned if the value cannot be determined.
  1321.  
  1322.     """
  1323.     return uname()[3]
  1324.  
  1325. def machine():
  1326.  
  1327.     """ Returns the machine type, e.g. 'i386'
  1328.  
  1329.         An empty string is returned if the value cannot be determined.
  1330.  
  1331.     """
  1332.     return uname()[4]
  1333.  
  1334. def processor():
  1335.  
  1336.     """ Returns the (true) processor name, e.g. 'amdk6'
  1337.  
  1338.         An empty string is returned if the value cannot be
  1339.         determined. Note that many platforms do not provide this
  1340.         information or simply return the same value as for machine(),
  1341.         e.g.  NetBSD does this.
  1342.  
  1343.     """
  1344.     return uname()[5]
  1345.  
  1346. ### Various APIs for extracting information from sys.version
  1347.  
  1348. _sys_version_parser = re.compile(
  1349.     r'([\w.+]+)\s*'
  1350.     '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1351.     '\[([^\]]+)\]?')
  1352.  
  1353. _jython_sys_version_parser = re.compile(
  1354.     r'([\d\.]+)')
  1355.  
  1356. _ironpython_sys_version_parser = re.compile(
  1357.     r'IronPython\s*'
  1358.     '([\d\.]+)'
  1359.     '(?: \(([\d\.]+)\))?'
  1360.     ' on (.NET [\d\.]+)')
  1361.  
  1362. _sys_version_cache = {}
  1363.  
  1364. def _sys_version(sys_version=None):
  1365.  
  1366.     """ Returns a parsed version of Python's sys.version as tuple
  1367.         (name, version, branch, revision, buildno, builddate, compiler)
  1368.         referring to the Python implementation name, version, branch,
  1369.         revision, build number, build date/time as string and the compiler
  1370.         identification string.
  1371.  
  1372.         Note that unlike the Python sys.version, the returned value
  1373.         for the Python version will always include the patchlevel (it
  1374.         defaults to '.0').
  1375.  
  1376.         The function returns empty strings for tuple entries that
  1377.         cannot be determined.
  1378.  
  1379.         sys_version may be given to parse an alternative version
  1380.         string, e.g. if the version was read from a different Python
  1381.         interpreter.
  1382.  
  1383.     """
  1384.     # Get the Python version
  1385.     if sys_version is None:
  1386.         sys_version = sys.version
  1387.  
  1388.     # Try the cache first
  1389.     result = _sys_version_cache.get(sys_version, None)
  1390.     if result is not None:
  1391.         return result
  1392.  
  1393.     # Parse it
  1394.     if sys_version[:10] == 'IronPython':
  1395.         # IronPython
  1396.         name = 'IronPython'
  1397.         match = _ironpython_sys_version_parser.match(sys_version)
  1398.         if match is None:
  1399.             raise ValueError(
  1400.                 'failed to parse IronPython sys.version: %s' %
  1401.                 repr(sys_version))
  1402.         version, alt_version, compiler = match.groups()
  1403.         branch = ''
  1404.         revision = ''
  1405.         buildno = ''
  1406.         builddate = ''
  1407.  
  1408.     elif sys.platform[:4] == 'java':
  1409.         # Jython
  1410.         name = 'Jython'
  1411.         match = _jython_sys_version_parser.match(sys_version)
  1412.         if match is None:
  1413.             raise ValueError(
  1414.                 'failed to parse Jython sys.version: %s' %
  1415.                 repr(sys_version))
  1416.         version, = match.groups()
  1417.         branch = ''
  1418.         revision = ''
  1419.         compiler = sys.platform
  1420.         buildno = ''
  1421.         builddate = ''
  1422.  
  1423.     else:
  1424.         # CPython
  1425.         match = _sys_version_parser.match(sys_version)
  1426.         if match is None:
  1427.             raise ValueError(
  1428.                 'failed to parse CPython sys.version: %s' %
  1429.                 repr(sys_version))
  1430.         version, buildno, builddate, buildtime, compiler = \
  1431.               match.groups()
  1432.         if hasattr(sys, 'subversion'):
  1433.             # sys.subversion was added in Python 2.5
  1434.             name, branch, revision = sys.subversion
  1435.         else:
  1436.             name = 'CPython'
  1437.             branch = ''
  1438.             revision = ''
  1439.         builddate = builddate + ' ' + buildtime
  1440.  
  1441.     # Add the patchlevel version if missing
  1442.     l = string.split(version, '.')
  1443.     if len(l) == 2:
  1444.         l.append('0')
  1445.         version = string.join(l, '.')
  1446.  
  1447.     # Build and cache the result
  1448.     result = (name, version, branch, revision, buildno, builddate, compiler)
  1449.     _sys_version_cache[sys_version] = result
  1450.     return result
  1451.  
  1452. def _test_sys_version():
  1453.  
  1454.     _sys_version_cache.clear()
  1455.     for input, output in (
  1456.         ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
  1457.          ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
  1458.         ('IronPython 1.0.60816 on .NET 2.0.50727.42',
  1459.          ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
  1460.         ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
  1461.          ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
  1462.         ):
  1463.         parsed = _sys_version(input)
  1464.         if parsed != output:
  1465.             print (input, parsed)
  1466.  
  1467. def python_implementation():
  1468.  
  1469.     """ Returns a string identifying the Python implementation.
  1470.  
  1471.         Currently, the following implementations are identified:
  1472.         'CPython' (C implementation of Python),
  1473.         'IronPython' (.NET implementation of Python),
  1474.         'Jython' (Java implementation of Python).
  1475.  
  1476.     """
  1477.     return _sys_version()[0]
  1478.  
  1479. def python_version():
  1480.  
  1481.     """ Returns the Python version as string 'major.minor.patchlevel'
  1482.  
  1483.         Note that unlike the Python sys.version, the returned value
  1484.         will always include the patchlevel (it defaults to 0).
  1485.  
  1486.     """
  1487.     return _sys_version()[1]
  1488.  
  1489. def python_version_tuple():
  1490.  
  1491.     """ Returns the Python version as tuple (major, minor, patchlevel)
  1492.         of strings.
  1493.  
  1494.         Note that unlike the Python sys.version, the returned value
  1495.         will always include the patchlevel (it defaults to 0).
  1496.  
  1497.     """
  1498.     return tuple(string.split(_sys_version()[1], '.'))
  1499.  
  1500. def python_branch():
  1501.  
  1502.     """ Returns a string identifying the Python implementation
  1503.         branch.
  1504.  
  1505.         For CPython this is the Subversion branch from which the
  1506.         Python binary was built.
  1507.  
  1508.         If not available, an empty string is returned.
  1509.  
  1510.     """
  1511.  
  1512.     return _sys_version()[2]
  1513.  
  1514. def python_revision():
  1515.  
  1516.     """ Returns a string identifying the Python implementation
  1517.         revision.
  1518.  
  1519.         For CPython this is the Subversion revision from which the
  1520.         Python binary was built.
  1521.  
  1522.         If not available, an empty string is returned.
  1523.  
  1524.     """
  1525.     return _sys_version()[3]
  1526.  
  1527. def python_build():
  1528.  
  1529.     """ Returns a tuple (buildno, builddate) stating the Python
  1530.         build number and date as strings.
  1531.  
  1532.     """
  1533.     return _sys_version()[4:6]
  1534.  
  1535. def python_compiler():
  1536.  
  1537.     """ Returns a string identifying the compiler used for compiling
  1538.         Python.
  1539.  
  1540.     """
  1541.     return _sys_version()[6]
  1542.  
  1543. ### The Opus Magnum of platform strings :-)
  1544.  
  1545. _platform_cache = {}
  1546.  
  1547. def platform(aliased=0, terse=0):
  1548.  
  1549.     """ Returns a single string identifying the underlying platform
  1550.         with as much useful information as possible (but no more :).
  1551.  
  1552.         The output is intended to be human readable rather than
  1553.         machine parseable. It may look different on different
  1554.         platforms and this is intended.
  1555.  
  1556.         If "aliased" is true, the function will use aliases for
  1557.         various platforms that report system names which differ from
  1558.         their common names, e.g. SunOS will be reported as
  1559.         Solaris. The system_alias() function is used to implement
  1560.         this.
  1561.  
  1562.         Setting terse to true causes the function to return only the
  1563.         absolute minimum information needed to identify the platform.
  1564.  
  1565.     """
  1566.     result = _platform_cache.get((aliased, terse), None)
  1567.     if result is not None:
  1568.         return result
  1569.  
  1570.     # Get uname information and then apply platform specific cosmetics
  1571.     # to it...
  1572.     system,node,release,version,machine,processor = uname()
  1573.     if machine == processor:
  1574.         processor = ''
  1575.     if aliased:
  1576.         system,release,version = system_alias(system,release,version)
  1577.  
  1578.     if system == 'Windows':
  1579.         # MS platforms
  1580.         rel,vers,csd,ptype = win32_ver(version)
  1581.         if terse:
  1582.             platform = _platform(system,release)
  1583.         else:
  1584.             platform = _platform(system,release,version,csd)
  1585.  
  1586.     elif system in ('Linux',):
  1587.         # Linux based systems
  1588.         distname,distversion,distid = dist('')
  1589.         if distname and not terse:
  1590.             platform = _platform(system,release,machine,processor,
  1591.                                  'with',
  1592.                                  distname,distversion,distid)
  1593.         else:
  1594.             # If the distribution name is unknown check for libc vs. glibc
  1595.             libcname,libcversion = libc_ver(sys.executable)
  1596.             platform = _platform(system,release,machine,processor,
  1597.                                  'with',
  1598.                                  libcname+libcversion)
  1599.     elif system == 'Java':
  1600.         # Java platforms
  1601.         r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
  1602.         if terse or not os_name:
  1603.             platform = _platform(system,release,version)
  1604.         else:
  1605.             platform = _platform(system,release,version,
  1606.                                  'on',
  1607.                                  os_name,os_version,os_arch)
  1608.  
  1609.     elif system == 'MacOS':
  1610.         # MacOS platforms
  1611.         if terse:
  1612.             platform = _platform(system,release)
  1613.         else:
  1614.             platform = _platform(system,release,machine)
  1615.  
  1616.     else:
  1617.         # Generic handler
  1618.         if terse:
  1619.             platform = _platform(system,release)
  1620.         else:
  1621.             bits,linkage = architecture(sys.executable)
  1622.             platform = _platform(system,release,machine,processor,bits,linkage)
  1623.  
  1624.     _platform_cache[(aliased, terse)] = platform
  1625.     return platform
  1626.  
  1627. ### Command line interface
  1628.  
  1629. if __name__ == '__main__':
  1630.     # Default is to print the aliased verbose platform string
  1631.     terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1632.     aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1633.     print platform(aliased,terse)
  1634.     sys.exit(0)
  1635.